package com.baobao.service;

import com.baobao.dao.CourseDAO;

import com.baobao.domain.Course;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

/**
 * Spring service that handles CRUD requests for Course entities
 * 
 */

@Service("CourseService")
@Transactional
public class CourseServiceImpl implements CourseService {

	/**
	 * DAO injected by Spring that manages Course entities
	 * 
	 */
	@Autowired
	private CourseDAO courseDAO;

	/**
	 * Instantiates a new CourseServiceImpl.
	 *
	 */
	public CourseServiceImpl() {
	}

	/**
	 * Delete an existing Course entity
	 * 
	 */
	@Transactional
	public void deleteCourse(Course course) {
		courseDAO.remove(course);
		courseDAO.flush();
	}

	/**
	 * Load an existing Course entity
	 * 
	 */
	@Transactional
	public Set<Course> loadCourses() {
		return courseDAO.findAllCourses();
	}

	/**
	 * Return all Course entity
	 * 
	 */
	@Transactional
	public List<Course> findAllCourses(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Course>(courseDAO.findAllCourses(startResult, maxRows));
	}

	/**
	 */
	@Transactional
	public Course findCourseByPrimaryKey(String banjiId, Integer weekDay, Integer seqNo) {
		return courseDAO.findCourseByPrimaryKey(banjiId, weekDay, seqNo);
	}

	/**
	 * Save an existing Course entity
	 * 
	 */
	@Transactional
	public void saveCourse(Course course) {
		Course existingCourse = courseDAO.findCourseByPrimaryKey(course.getBanjiId(), course.getWeekDay(), course.getSeqNo());

		if (existingCourse != null) {
			if (existingCourse != course) {
				existingCourse.setBanjiId(course.getBanjiId());
				existingCourse.setWeekDay(course.getWeekDay());
				existingCourse.setSeqNo(course.getSeqNo());
				existingCourse.setName(course.getName());
				existingCourse.setStartTime(course.getStartTime());
				existingCourse.setEndTime(course.getEndTime());
			}
			course = courseDAO.store(existingCourse);
		} else {
			course = courseDAO.store(course);
		}
		courseDAO.flush();
	}

	/**
	 * Return a count of all Course entity
	 * 
	 */
	@Transactional
	public Integer countCourses() {
		return ((Long) courseDAO.createQuerySingleResult("select count(*) from Course o").getSingleResult()).intValue();
	}
}
